package cn.softwin.controller;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.druid.proxy.jdbc.JdbcParameter.TYPE;
import com.sun.prism.Image;
import com.sun.xml.internal.stream.util.BufferAllocator;

/**
 * Servlet implementation class ImgServlet
 */
@WebServlet("/ImgServlet")
public class ImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImgServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		 this.doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		doGet(request, response);
		int w=100;
		int h=25;
		//1.创建对象 用来保存图片 用BufferedImage方法
		BufferedImage bimg=new BufferedImage(w, h, BufferedImage.TYPE_INT_BGR);
		//2.美化图片 背景色 边框
		Graphics g = bimg.getGraphics();//虚拟设置一个画笔对象
		g.setColor(Color.white);//设置画笔颜色
		g.fillRect(0, 0, w, h);//填充背景
		//美化边框
		g.setColor(Color.black);
		g.drawRect(0, 0, w-1, h-1);
		String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		Random ran = new Random();
		//随机生成一个坐标，摆放验证码字符
		StringBuilder sb=new StringBuilder();
		for(int i=1;i<=5;i++) {
			int nextInt = ran.nextInt(str.length());
			char charAt = str.charAt(nextInt);//获取字符
			sb.append(charAt);
			
			g.drawString(charAt+"", w/8*i, h/2);//写验证码到图片   /* (charAt, w/i, h/2); */
		}
		String sbstr = sb.toString();
		HttpSession ses = request.getSession();
		ses.setAttribute("yzm", sbstr);
//		Object yzm = ses.getAttribute(sbstr);
		
		//画干扰线
		g.setColor(Color.red);
		//随机生成干扰线坐标
		for(int i=0;i<3;i++) {
			int x1 = ran.nextInt(w);
			int x2 = ran.nextInt(w);
			int y1 = ran.nextInt(h);
			int y2 = ran.nextInt(h);
			g.drawLine(x1, y1, x2, y2);
		}
		ImageIO.write(bimg,"jpg",response.getOutputStream());
		
		
	}

}
